在 SwiftUI 中,手勢識別非常簡便且強大。透過結合不同的手勢識別器(如點擊、拖曳、長按等),你可以為視圖添加互動性。以下是一個簡單的教學,展示如何使用 GestureRecognizer 和 SwiftUI 來識別手勢。
點擊手勢 (TapGesture)
struct TapGestureView: View {
    @State private var tapCount = 0
    var body: some View {
        Text("Tap count: \(tapCount)")
            .padding()
            .onTapGesture {
                tapCount += 1
            }
    }
}
上面的範例使用 onTapGesture,每次點擊文本時,tapCount 就會增加。
拖曳手勢 (DragGesture)
struct DragGestureView: View {
    @State private var offset: CGSize = .zero
    var body: some View {
        Text("Drag me!")
            .padding()
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)
            .offset(offset)
            .gesture(
                DragGesture()
                    .onChanged { gesture in
                        offset = gesture.translation
                    }
                    .onEnded { _ in
                        offset = .zero
                    }
            )
    }
}
這裡使用 DragGesture 讓使用者可以拖曳文字視圖,拖曳後會回到初始位置。
長按手勢 (LongPressGesture)
struct LongPressGestureView: View {
    @State private var isPressed = false
    var body: some View {
        Text(isPressed ? "Pressed" : "Long Press Me")
            .padding()
            .background(isPressed ? Color.red : Color.green)
            .foregroundColor(.white)
            .cornerRadius(10)
            .onLongPressGesture(minimumDuration: 1.0) {
                isPressed.toggle()
            }
    }
}
在這個範例中,使用 onLongPressGesture 來觸發長按行為,當長按超過 1 秒時,背景顏色會變更。
SwiftUI 提供了簡單直觀的方式來處理手勢,你可以根據應用場景靈活應用這些手勢來提升用戶體驗。